{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "import talib\n",
    "from sqlalchemy import create_engine\n",
    "TABLE_FUND_DAY_K_DATA = \"shenge_money_fund_day_k_data\"\n",
    "import mplfinance as mpf\n",
    "import tqdm\n",
    "import time\n",
    "import requests\n",
    "\n",
    "def connect_db():\n",
    "    connect_info = 'mysql+pymysql://paqi:chs518518!@rm-bp1v9plylv4340as7qo.mysql.rds.aliyuncs.com:3306/paqi?charset=utf8'\n",
    "    engine = create_engine(connect_info)\n",
    "    return engine\n",
    "\n",
    "def LOW(df,n):\n",
    "    mins = []\n",
    "    for index,row in df.iterrows():\n",
    "        tdate = row['tdate']\n",
    "        dff = df[df['tdate']<=tdate]\n",
    "        if len(dff) >= n:\n",
    "            dff = dff.tail(n)\n",
    "        min = dff['low'].min()\n",
    "        mins.append(min)\n",
    "    return pd.Series(mins).astype('float')\n",
    "\n",
    "def HIGH(df,n):\n",
    "    maxs = []\n",
    "    for index,row in df.iterrows():\n",
    "        tdate = row['tdate']\n",
    "        dff = df[df['tdate']<=tdate]\n",
    "        if len(dff) >= n:\n",
    "            dff = dff.tail(n)\n",
    "        max = dff['high'].max()\n",
    "        maxs.append(max)\n",
    "    return pd.Series(maxs).astype('float')\n",
    "\n",
    "def judeBuyPoint(ktype,df_cp):\n",
    "    if (ktype == 101 or ktype==102) and len(df_cp) >= 5:\n",
    "        df_judge = df_cp.tail(5)\n",
    "        lastFivDatas = []\n",
    "        for index, row in df_judge.iterrows():\n",
    "            lastFivDatas.append(dict(row))\n",
    "\n",
    "        isUp = False\n",
    "        isDown = False\n",
    "        if lastFivDatas[4][\"D\"] <= lastFivDatas[4][\"K\"] or lastFivDatas[3][\"D\"] <= lastFivDatas[3][\"K\"]:\n",
    "            isUp = True\n",
    "        if lastFivDatas[0][\"D\"] > lastFivDatas[0][\"K\"] and lastFivDatas[1][\"D\"] > lastFivDatas[1][\"K\"] and \\\n",
    "                lastFivDatas[2][\"D\"] > lastFivDatas[2][\"K\"]:\n",
    "            isDown = True\n",
    "        if lastFivDatas[4][\"D\"] > lastFivDatas[4][\"K\"] and lastFivDatas[3][\"D\"] < lastFivDatas[3][\"K\"]:\n",
    "            isUp = False\n",
    "        return isDown and isUp\n",
    "    else:\n",
    "        if (ktype == 103) and len(df_cp) >= 3:\n",
    "            df_judge = df_cp.tail(3)\n",
    "            lastFivDatas = []\n",
    "            for index, row in df_judge.iterrows():\n",
    "                lastFivDatas.append(dict(row))\n",
    "\n",
    "            isUp = False\n",
    "            isDown = False\n",
    "            if lastFivDatas[2][\"D\"] < lastFivDatas[2][\"K\"]:\n",
    "                isUp = True\n",
    "            if lastFivDatas[0][\"D\"] > lastFivDatas[0][\"K\"] and lastFivDatas[1][\"D\"] > lastFivDatas[1][\"K\"]:\n",
    "                isDown = True\n",
    "            return isDown and isUp\n",
    "        else:\n",
    "            return False\n",
    "\n",
    "\n",
    "def getRealTimeFundData(code):\n",
    "    code = str(code)\n",
    "    if code[0] =='5':\n",
    "        code = \"sh\"+code\n",
    "    \n",
    "    if code[0] == '1':\n",
    "        code = \"sz\"+code\n",
    "    r2 = requests.get(url=\"https://hq.sinajs.cn/list=%s\"% code) \n",
    "    datas = str.split(r2.text,\"\\\"\")\n",
    "    bbs = str.split(datas[1],\",\")\n",
    "    detail ={}\n",
    "    detail[\"name\"]= bbs[0]\n",
    "    detail[\"close\"]= bbs[3]\n",
    "    detail[\"open\"]=bbs[1]\n",
    "    detail[\"high\"]=bbs[4]\n",
    "    detail[\"low\"]=bbs[5]\n",
    "    detail['tdate'] =bbs[30] \n",
    "    return detail\n",
    "\n",
    "\n",
    "def createAndSaveBuyPointData(ktype,codes):\n",
    "    conn = connect_db()\n",
    "    TABLE_FUND_DAY_BUY_DATA ='shenge_money_buy_point'\n",
    "    datas ={}\n",
    "    year = range(len(codes))\n",
    "    flag = range(len(codes))\n",
    "    type = range(len(codes))\n",
    "    ktypes = range(len(codes))\n",
    "    datas['code'] = codes\n",
    "    datas['year'] = year\n",
    "    datas['flag'] = flag\n",
    "    datas['type'] = type\n",
    "    datas['ktype'] = ktypes\n",
    "    df = pd.DataFrame(datas)\n",
    "    df['year'] =time.strftime('%Y')\n",
    "    if ktype==102:\n",
    "        df['flag'] =time.strftime('%W')\n",
    "    if ktype==101:\n",
    "        df['flag'] =time.strftime('%Y-%m-%d')\n",
    "    if ktype == 103:\n",
    "        df['flag'] = time.strftime('%m')\n",
    "    df['type'] ='SKDJ'\n",
    "    df['ktype'] = ktype\n",
    "    df.to_sql(TABLE_FUND_DAY_BUY_DATA, con=conn,  if_exists=\"append\",index=False)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "metadata": {},
   "outputs": [
    {
     "ename": "FileNotFoundError",
     "evalue": "[WinError 2] 系统找不到指定的文件。",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mFileNotFoundError\u001b[0m                         Traceback (most recent call last)",
      "\u001b[1;32m~\\AppData\\Local\\Temp/ipykernel_14376/1762288714.py\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[0;32m      4\u001b[0m \u001b[1;31m#     os.system(\"del  %s\" % (path))\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      5\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 6\u001b[1;33m \u001b[0mout\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0msubprocess\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mrun\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"dir\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m      7\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      8\u001b[0m \u001b[0mout\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;32mC:\\ProgramData\\Anaconda3\\lib\\subprocess.py\u001b[0m in \u001b[0;36mrun\u001b[1;34m(input, capture_output, timeout, check, *popenargs, **kwargs)\u001b[0m\n\u001b[0;32m    503\u001b[0m         \u001b[0mkwargs\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;34m'stderr'\u001b[0m\u001b[1;33m]\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mPIPE\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m    504\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m--> 505\u001b[1;33m     \u001b[1;32mwith\u001b[0m \u001b[0mPopen\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m*\u001b[0m\u001b[0mpopenargs\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;33m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[1;33m)\u001b[0m \u001b[1;32mas\u001b[0m \u001b[0mprocess\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m    506\u001b[0m         \u001b[1;32mtry\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m    507\u001b[0m             \u001b[0mstdout\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mstderr\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mprocess\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mcommunicate\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0minput\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mtimeout\u001b[0m\u001b[1;33m=\u001b[0m\u001b[0mtimeout\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;32mC:\\ProgramData\\Anaconda3\\lib\\subprocess.py\u001b[0m in \u001b[0;36m__init__\u001b[1;34m(self, args, bufsize, executable, stdin, stdout, stderr, preexec_fn, close_fds, shell, cwd, env, universal_newlines, startupinfo, creationflags, restore_signals, start_new_session, pass_fds, user, group, extra_groups, encoding, errors, text, umask)\u001b[0m\n\u001b[0;32m    949\u001b[0m                             encoding=encoding, errors=errors)\n\u001b[0;32m    950\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m--> 951\u001b[1;33m             self._execute_child(args, executable, preexec_fn, close_fds,\n\u001b[0m\u001b[0;32m    952\u001b[0m                                 \u001b[0mpass_fds\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mcwd\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0menv\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m    953\u001b[0m                                 \u001b[0mstartupinfo\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mcreationflags\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mshell\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;32mC:\\ProgramData\\Anaconda3\\lib\\subprocess.py\u001b[0m in \u001b[0;36m_execute_child\u001b[1;34m(self, args, executable, preexec_fn, close_fds, pass_fds, cwd, env, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite, unused_restore_signals, unused_gid, unused_gids, unused_uid, unused_umask, unused_start_new_session)\u001b[0m\n\u001b[0;32m   1418\u001b[0m             \u001b[1;31m# Start the process\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m   1419\u001b[0m             \u001b[1;32mtry\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m-> 1420\u001b[1;33m                 hp, ht, pid, tid = _winapi.CreateProcess(executable, args,\n\u001b[0m\u001b[0;32m   1421\u001b[0m                                          \u001b[1;31m# no special security\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m   1422\u001b[0m                                          \u001b[1;32mNone\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;32mNone\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;31mFileNotFoundError\u001b[0m: [WinError 2] 系统找不到指定的文件。"
     ]
    }
   ],
   "source": [
    "import os;\n",
    "import subprocess\n",
    "# def deletePics(path):\n",
    "#     os.system(\"del  %s\" % (path))\n",
    "\n",
    "out = subprocess.run(\"dir\")\n",
    "\n",
    "out"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# ktype k线级别 \n",
    "# 101 日 \n",
    "# 102 周 \n",
    "# 103 月\n",
    "# 是否保存图片\n",
    "def calSkdj(ktype,savepic,realtime):\n",
    "    conn = connect_db()\n",
    "    sql = \"SELECT  DISTINCT code FROM %s  \" % TABLE_FUND_DAY_K_DATA\n",
    "    df_fund_code = pd.read_sql(sql=sql,con=conn)\n",
    "    codes = list(df_fund_code['code'])\n",
    "\n",
    "    \n",
    "\n",
    "    buyCodes =[]\n",
    "    for code in tqdm.tqdm(codes):\n",
    "        try:\n",
    "             sql = \"SELECT  * FROM %s WHERE code= %s AND ktype=%s \" % (TABLE_FUND_DAY_K_DATA, code,ktype)\n",
    "            if realtime:\n",
    "                current = getRealTimeFundData(code)\n",
    "                sql = \"SELECT  * FROM %s WHERE code= %s AND ktype=%s AND tdate<'%s'\" % (TABLE_FUND_DAY_K_DATA, code,ktype,current['tdate'])\n",
    "            df_code = pd.read_sql(sql=sql, con=conn)\n",
    "            df_code.loc(len(df_code)) = pd.Series(current)\n",
    "            LOWV = LOW(df_code, 9)\n",
    "            HIGV = HIGH(df_code, 9)\n",
    "            import numpy as np\n",
    "            df_float = df_code['close'].astype('float')\n",
    "            cal1 = (df_float - LOWV)\n",
    "            cal2 = (HIGV - LOWV)\n",
    "            cal1 = cal1 / cal2 * 100\n",
    "            RSV = talib.EMA(cal1, 3)\n",
    "            K = talib.EMA(RSV, 3)\n",
    "            D = talib.MA(K, 3)\n",
    "            df_cp = df_code.copy()\n",
    "\n",
    "            df_cp.insert(df_cp.shape[1], 'K', K)\n",
    "            df_cp.insert(df_cp.shape[1], 'D', D)\n",
    "            df_cp = df_cp.dropna()\n",
    "\n",
    "            canBuy =judeBuyPoint(ktype, df_cp)\n",
    "            #talib.stream_CDLHARAMICROSS()\n",
    "            if canBuy:\n",
    "                buyCodes.append(code)\n",
    "\n",
    "\n",
    "\n",
    "            if savepic and canBuy:\n",
    "                df_cp2 = df_cp.rename(columns={\"open\": \"Open\", \"close\": \"Close\", \"high\": \"High\", \"low\": \"Low\"}).tail(60)\n",
    "                df_cp2[\"Open\"] = df_cp2[\"K\"].astype(\"float\")\n",
    "\n",
    "                df_cp2[\"Close\"] = df_cp2[\"D\"].astype(\"float\")\n",
    "                df_cp2[\"High\"] = df_cp2[\"D\"].astype(\"float\")\n",
    "                df_cp2[\"Low\"] = df_cp2[\"K\"].astype(\"float\")\n",
    "                df_cp2['tdate'] = pd.to_datetime(df_cp2['tdate'])\n",
    "                df_cp2.set_index(\"tdate\", inplace=True)\n",
    "\n",
    "\n",
    "                apdict = mpf.make_addplot(df_cp2[['D', 'K']])\n",
    "                save =None\n",
    "                if ktype == 101:\n",
    "                    save = dict(fname='./tmp/%s日线SKDJ.jpg' % code, dpi=30, pad_inches=0.25)\n",
    "                if ktype == 102:\n",
    "                    save = dict(fname='./tmp/%s周线SKDJ.jpg' % code, dpi=30, pad_inches=0.25)\n",
    "                if ktype == 103:\n",
    "                    save = dict(fname='./tmp/%s月线SKDJ.jpg' % code, dpi=30, pad_inches=0.25)\n",
    "\n",
    "                if save == None:\n",
    "                    return\n",
    "\n",
    "                mpf.plot(df_cp2, volume=False, addplot=apdict, type='candle', figscale=1.5, figratio=(4, 1), style=\"binance\",\n",
    "                         savefig=save)\n",
    "        except Exception as e:\n",
    "            continue\n",
    "    return buyCodes"
   ]
  }
 ],
 "metadata": {
  "interpreter": {
   "hash": "31f2aee4e71d21fbe5cf8b01ff0e069b9275f58929596ceb00d14d90e3e16cd6"
  },
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.7"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
